"use client";

import { useState, useRef, useEffect, use } from "react";
import AnimatedSkeleton from "../components/AnimatedSkeleton";
import LivePoseTracker from "../components/LivePoseTracker";
import ScoreModal from "../components/ScoreModal";
import { usePoseDetection, Landmark } from "../hooks/usePoseDetection";

// Dance-themed phrases for typewriter effect
const DANCE_PHRASES = [
  "Dance to the Beat",
  "Move Your Body",
  "Feel the Rhythm",
  "Strike a Pose",
  "Get in the Groove",
  "Own the Dance Floor",
  "Make Some Magic",
  "Express Yourself",
  "Turn Up the Heat",
  "Vibe with the Music",
  "Let Loose Tonight",
  "Show Your Style",
];

// Just Dance background video IDs from the playlist
const JUST_DANCE_VIDEOS = [
  "wiV6r-xr4qg", "UmnDovvESoM", "xXARtL4-4e4", "-jHiKpy3vZU",
  "xR7hBR3yvvE", "IZ0c4gsvaDQ", "Q3MVadhvbjc", "3T0bHZBASPE",
  "HWdETRlLq7M", "bIG93CAUb0s"
];

interface MotionMetadata {
  num_frames: number;
  duration: number;
  fps: number;
}

// Timestamps for pose markers (in seconds)
const TIMESTAMPS = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0];

// Ready countdown component
function ReadyCountdown({ onComplete }: { onComplete: () => void }) {
  const [text, setText] = useState("Ready to Dance!");
  const [fadeOut, setFadeOut] = useState(false);

  useEffect(() => {
    // Show "Ready to Dance!" for 1.5s
    const timer1 = setTimeout(() => {
      setText("Let's Go!");
    }, 1500);

    // Show "Let's Go!" for 1s, then start fade
    const timer2 = setTimeout(() => {
      setFadeOut(true);
    }, 2500);

    // Complete transition after fade
    const timer3 = setTimeout(() => {
      onComplete();
    }, 3000);

    return () => {
      clearTimeout(timer1);
      clearTimeout(timer2);
      clearTimeout(timer3);
    };
  }, [onComplete]);

  return (
    <div
      className={`text-center transition-opacity duration-500 ${
        fadeOut ? 'opacity-0' : 'opacity-100'
      }`}
    >
      <h1
        className="text-8xl font-bold text-white mb-8 animate-pulse"
        style={{
          letterSpacing: "-0.02em",
          textShadow: "0 0 40px rgba(255, 255, 255, 0.5)",
        }}
      >
        {text}
      </h1>
    </div>
  );
}

export default function SongPage({
  params,
}: {
  params: Promise<{ songId: string }>;
}) {
  const { songId } = use(params);

  // Stage management
  const [stage, setStage] = useState<'landing' | 'loading' | 'ready' | 'dancing'>('landing');
  const [playerCount, setPlayerCount] = useState<1 | 2 | null>(null);
  
  // Motion data
  const [motionLoaded, setMotionLoaded] = useState(false);
  const [motionMetadata, setMotionMetadata] = useState<MotionMetadata | null>(null);
  const [motionFrames, setMotionFrames] = useState<Landmark[][]>([]);
  const [message, setMessage] = useState<string>("");
  const [motionError, setMotionError] = useState<string | null>(null);

  // Downbeat timestamps (dynamically fetched)
  const [downbeatTimestamps, setDownbeatTimestamps] = useState<number[]>([]);

  // Audio duration
  const [audioDuration, setAudioDuration] = useState<number | null>(null);

  // Animation state
  const [currentTime, setCurrentTime] = useState(0);
  const [referenceLandmarks, setReferenceLandmarks] = useState<Landmark[] | null>(null);

  // Pose snapshots at timestamps
  const [poseSnapshots, setPoseSnapshots] = useState<Map<number, Landmark[]>>(new Map());
  
  // Score tracking
  const [currentScore, setCurrentScore] = useState(0);
  const currentScoreRef = useRef<number>(0); // Use ref for immediate access to latest score
  const [downbeatScores, setDownbeatScores] = useState<number[]>([]);
  const lastProcessedDownbeat = useRef<number>(-1);
  const [showScoreModal, setShowScoreModal] = useState(false);
  const [finalScore, setFinalScore] = useState(0);
  
  // Feedback display
  const [feedbackText, setFeedbackText] = useState<string>("");
  const [showFeedback, setShowFeedback] = useState(false);
  const feedbackTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  // Typewriter effect state
  const [phraseIndex, setPhraseIndex] = useState(0);
  const [displayedText, setDisplayedText] = useState("");
  const [isDeleting, setIsDeleting] = useState(false);
  
  // Background video
  const [backgroundVideoId] = useState(() => {
    return JUST_DANCE_VIDEOS[Math.floor(Math.random() * JUST_DANCE_VIDEOS.length)];
  });
  
  // Refs
  const audioRef = useRef<HTMLAudioElement>(null);
  const animationFrameRef = useRef<number | null>(null);
  const startTimeRef = useRef<number>(0);

  const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:8000";
  const audioUrl = `https://cdn1.suno.ai/${songId}.mp3`;

  // Initialize pose detection
  const { isReady: isPoseReady } = usePoseDetection();

  // Get feedback text based on score
  const getFeedbackText = (score: number): string => {
    console.log("Feedback score:", score);
    if (score >= 95) return "PERFECT! ⭐";
    if (score >= 85) return "AMAZING! 🔥";
    if (score >= 75) return "GREAT! 💫";
    if (score >= 65) return "GOOD! ✨";
    if (score >= 50) return "NICE! 👍";
    return "KEEP GOING! 💪";
  };

  // Show feedback with animation
  const showDownbeatFeedback = (score: number) => {
    console.log("🎯 Showing feedback for score:", score);
    const feedback = getFeedbackText(score);
    console.log("Feedback text:", feedback);
    setFeedbackText(feedback);
    setShowFeedback(true);
    console.log("showFeedback set to true");

    // Clear any existing timeout
    if (feedbackTimeoutRef.current) {
      clearTimeout(feedbackTimeoutRef.current);
    }

    // Hide feedback after 1 second
    feedbackTimeoutRef.current = setTimeout(() => {
      console.log("Hiding feedback");
      setShowFeedback(false);
    }, 1000);
  };

  // Debug: Track feedback state changes
  useEffect(() => {
    console.log("🔔 showFeedback changed to:", showFeedback);
    console.log("🔔 feedbackText is:", feedbackText);
  }, [showFeedback, feedbackText]);

  // Typewriter effect - only run on landing page
  useEffect(() => {
    if (stage !== 'landing') return;

    const currentPhrase = DANCE_PHRASES[phraseIndex];
    const typingSpeed = 50;
    const deletingSpeed = 30;
    const pauseAfterComplete = 1000;
    const pauseAfterDelete = 200;

    const timeout = setTimeout(() => {
      if (!isDeleting && displayedText === currentPhrase) {
        setIsDeleting(true);
      } else if (isDeleting && displayedText === "") {
        setIsDeleting(false);
        setPhraseIndex((prev) => (prev + 1) % DANCE_PHRASES.length);
      } else if (isDeleting) {
        setDisplayedText(currentPhrase.substring(0, displayedText.length - 1));
      } else {
        setDisplayedText(currentPhrase.substring(0, displayedText.length + 1));
      }
    }, 
      !isDeleting && displayedText === currentPhrase ? pauseAfterComplete :
      isDeleting && displayedText === "" ? pauseAfterDelete :
      isDeleting ? deletingSpeed : typingSpeed
    );

    return () => clearTimeout(timeout);
  }, [displayedText, isDeleting, phraseIndex, stage]);

  // Fetch audio duration
  const fetchAudioDuration = async (): Promise<number> => {
    return new Promise((resolve, reject) => {
      const audio = new Audio(audioUrl);
      audio.addEventListener('loadedmetadata', () => {
        const duration = audio.duration;
        setAudioDuration(duration);
        resolve(duration);
      });
      audio.addEventListener('error', () => {
        reject(new Error('Failed to load audio'));
      });
    });
  };

  // Fetch motion data and downbeats concurrently
  const fetchMotionData = async () => {
    try {
      setStage('loading');
      setMessage("🎵 Loading audio...");
      setMotionError(null);

      // First, get the audio duration
      const duration = await fetchAudioDuration();
      console.log(`Audio duration: ${duration.toFixed(1)}s`);

      setMessage("🎵 Generating dance choreography and analyzing beats...");

      // Make both API calls concurrently with actual duration
      const [motionResponse, downbeatResponse] = await Promise.all([
        fetch(
          `${BACKEND_URL}/api/generate-motion?song_id=${encodeURIComponent(
            songId
          )}&start_time=0.0&end_time=${duration.toFixed(1)}`,
          {
        method: "POST",
          }
        ),
        fetch(
          `https://suno-ai--eric-downbeats-dev-web.modal.run/downbeats/${encodeURIComponent(
            songId
          )}`
        ),
      ]);

      if (!motionResponse.ok) {
        const error = await motionResponse.json();
        const errorMsg =
          typeof error.detail === "string"
            ? error.detail
            : error.message || "Failed to generate dance";
        setMotionError(errorMsg);
        setMessage(`❌ Error: ${errorMsg}`);
        return;
      }

      const motionData = await motionResponse.json();
      setMotionMetadata(motionData.metadata);
      setMotionFrames(motionData.frames);

      if (motionData.frames && motionData.frames.length > 0) {
        setReferenceLandmarks(motionData.frames[0]);
      }

      // Process downbeats
      let timestamps: number[] = [];
      if (downbeatResponse.ok) {
        const downbeatData = await downbeatResponse.json();

        // Filter for beat_number == 1 and extract timestamps
        if (downbeatData.downbeats && Array.isArray(downbeatData.downbeats)) {
          timestamps = downbeatData.downbeats
            .filter(([_, beatNumber]: [number, number]) => beatNumber === 1)
            .map(([timestamp]: [number, number]) => timestamp);

          console.log(`Extracted ${timestamps.length} downbeat timestamps:`, timestamps);
          setDownbeatTimestamps(timestamps);
        }
      } else {
        console.warn("Failed to fetch downbeats, using fallback timestamps");
        // Fallback to original hardcoded timestamps
        timestamps = TIMESTAMPS;
        setDownbeatTimestamps(timestamps);
      }

      // Extract pose snapshots at downbeat timestamps
      if (motionData.frames && motionData.frames.length > 0) {
        const fps = motionData.metadata.fps || 30;
        const snapshots = new Map<number, Landmark[]>();
        timestamps.forEach(timestamp => {
          const frameIndex = Math.floor(timestamp * fps);
          if (frameIndex >= 0 && frameIndex < motionData.frames.length) {
            snapshots.set(timestamp, motionData.frames[frameIndex]);
          }
        });
        setPoseSnapshots(snapshots);
      }

      setMotionLoaded(true);
      setMessage(
        `✅ Dance loaded! ${
          motionData.metadata.num_frames
        } frames, ${motionData.metadata.duration.toFixed(1)}s duration, ${timestamps.length} downbeats`
      );

      // Move to ready stage
      setTimeout(() => setStage('ready'), 1000);
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMsg =
        error instanceof Error
          ? error.message
          : "Failed to connect to server. Please try refreshing the page.";
      setMotionError(errorMsg);
      setMessage("❌ Connection error. Please check your network.");
    }
  };

  // Update reference skeleton based on elapsed time (independent of audio looping)
  const updateReferenceSkeleton = () => {
    if (!motionLoaded || motionFrames.length === 0) return;

    // Calculate elapsed time since animation started
    const now = performance.now();
    const elapsed = (now - startTimeRef.current) / 1000; // Convert to seconds
    setCurrentTime(elapsed);

    // Check if song has ended
    const songDuration = motionMetadata?.duration || audioDuration || 30;
    if (elapsed >= songDuration) {
      // Song ended - calculate final score and show modal
      if (downbeatScores.length > 0) {
        const avgScore = downbeatScores.reduce((a, b) => a + b, 0) / downbeatScores.length;
        setFinalScore(Math.round(avgScore));
      } else {
        setFinalScore(0);
      }
      setShowScoreModal(true);
      
      // Stop animation and audio
      if (audioRef.current) {
        audioRef.current.pause();
      }
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      return;
    }

    // Check for downbeat scoring
    for (const downbeat of downbeatTimestamps) {
      if (Math.abs(elapsed - downbeat) < 0.1 && downbeat !== lastProcessedDownbeat.current) {
        // We're at a downbeat - capture the current score from ref (most up-to-date)
        console.log(`⏱️ DOWNBEAT DETECTED at ${downbeat.toFixed(2)}s`);
        lastProcessedDownbeat.current = downbeat;
        const scoreAtDownbeat = currentScoreRef.current;
        setDownbeatScores(prev => [...prev, scoreAtDownbeat]);
        console.log(`📊 Downbeat at ${downbeat.toFixed(2)}s - Score: ${scoreAtDownbeat.toFixed(1)}`);
        
        // Show feedback above skeleton
        console.log("Calling showDownbeatFeedback...");
        showDownbeatFeedback(scoreAtDownbeat);
        break;
      }
    }

    const fps = motionMetadata?.fps || 30;
    const frameIndex = Math.floor(elapsed * fps) % motionFrames.length; // Loop through all frames

    if (frameIndex >= 0 && frameIndex < motionFrames.length) {
      setReferenceLandmarks(motionFrames[frameIndex]);
    }

    animationFrameRef.current = requestAnimationFrame(updateReferenceSkeleton);
  };

  // Start animation when entering dancing stage
  useEffect(() => {
    if (stage === 'dancing' && motionLoaded) {
      // Initialize start time
      startTimeRef.current = performance.now();
      
      // Start audio
      if (audioRef.current) {
        audioRef.current.currentTime = 0;
        audioRef.current.play().catch((error) => {
          console.error("Error playing audio:", error);
        });
      }

      // Start animation loop
      animationFrameRef.current = requestAnimationFrame(updateReferenceSkeleton);
    } else {
      // Stop audio and animation
      if (audioRef.current) {
        audioRef.current.pause();
      }
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    }

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      if (feedbackTimeoutRef.current) {
        clearTimeout(feedbackTimeoutRef.current);
      }
    };
  }, [stage, motionLoaded, motionFrames]);

  const handleStartDancing = () => {
    fetchMotionData();
  };

  const handleEndSong = () => {
    // Calculate final score from collected downbeat scores
    if (downbeatScores.length > 0) {
      const avgScore = downbeatScores.reduce((a, b) => a + b, 0) / downbeatScores.length;
      setFinalScore(Math.round(avgScore));
    } else {
      setFinalScore(0);
    }
    
    // Stop audio and animation
    if (audioRef.current) {
      audioRef.current.pause();
    }
    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current);
    }
    
    // Show score modal
    setShowScoreModal(true);
  };

  // STAGE 1: Landing Page
  if (stage === 'landing') {
  return (
      <div className="h-screen w-full bg-[#101012] overflow-hidden">
        <div className="relative flex h-full w-full flex-col overflow-hidden">
          {/* Background Image with Gradient */}
          <div className="absolute inset-0 z-0 h-full w-full">
            <div
              className="absolute inset-0 h-full w-full"
              style={{
                backgroundImage: `url(https://cdn-o.suno.com/Aura-1-Hero-Web.jpg)`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                mixBlendMode: "screen",
              }}
            />
            <div
              className="absolute inset-0"
              style={{
                background: `linear-gradient(180deg, rgba(16, 16, 18, 0.00) 0%, #101012 100%)`,
              }}
            />
          </div>

          {/* Logo */}
          <div className="fixed top-0 left-0 right-0 z-50 w-full p-5">
            <div className="flex items-center">
              <div className="flex flex-1 items-center gap-2">
                <img
                  src="https://cdn1.suno.ai/SystemLogo.svg"
                  alt="Suno"
                  className="h-8 w-auto"
                  style={{
                    filter: 'drop-shadow(0 0 8px rgba(0, 0, 0, 0.8))',
                  }}
                />
                <span 
                  className="text-xl font-medium text-white"
                  style={{
                    letterSpacing: "-0.01em",
                  }}
                >
                  Dancify
                </span>
              </div>
            </div>
          </div>

          {/* Hero Section */}
          <div className="relative z-10 flex min-h-screen flex-col items-center justify-center px-4">
            <div className="max-w-5xl text-center">
              <h1
                className="mb-3 text-6xl sm:text-7xl md:text-8xl lg:text-9xl font-medium text-white min-h-[1.2em]"
                style={{
                  lineHeight: "0.95",
                  letterSpacing: "-0.04em",
                }}
              >
                {displayedText}
                <span className="animate-pulse">|</span>
              </h1>
              <p 
                className="mb-6 text-lg sm:text-xl md:text-2xl text-[rgb(156,163,175)] max-w-2xl mx-auto font-normal"
                style={{
                  lineHeight: "1.5",
                  letterSpacing: "-0.01em",
                }}
              >
                Just Dance
              </p>

              {/* Player Selection */}
              <div className="mb-8 flex gap-4 items-center justify-center">
                <button
                  onClick={() => setPlayerCount(1)}
                  className={`px-6 py-3 rounded-full font-medium transition-all duration-200 flex items-center gap-2 ${
                    playerCount === 1 
                      ? 'bg-white text-[#101012]' 
                      : 'bg-[rgba(255,255,255,0.1)] text-white hover:bg-[rgba(255,255,255,0.15)]'
                  }`}
                  style={{ letterSpacing: "-0.01em" }}
                >
                  <svg 
                    className="w-5 h-5" 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    fill="currentColor"
                  >
                    <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                  </svg>
                  <span>1 Player</span>
                </button>
                <button
                  onClick={() => setPlayerCount(2)}
                  className={`px-6 py-3 rounded-full font-medium transition-all duration-200 flex items-center gap-2 ${
                    playerCount === 2 
                      ? 'bg-white text-[#101012]' 
                      : 'bg-[rgba(255,255,255,0.1)] text-white hover:bg-[rgba(255,255,255,0.15)]'
                  }`}
                  style={{ letterSpacing: "-0.01em" }}
                >
                  <svg 
                    className="w-5 h-5" 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    fill="currentColor"
                  >
                    <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5s-3 1.34-3 3 1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
                  </svg>
                  <span>2 Players</span>
                </button>
          </div>

              {/* Start Dancing Button */}
              <button
                onClick={handleStartDancing}
                disabled={!playerCount}
                className={`aura-button ${playerCount ? 'pulse-active' : ''}`}
                style={{
                  display: 'inline-flex',
                }}
              >
                <div className="aura-button-content">
                  <svg 
                    className="aura-button-icon" 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    fill="currentColor"
                  >
                    <path d="m9.35 8.232-2.446.244a.865.865 0 0 0-.78.859v7.558a3 3 0 0 0-.521-.042C4.165 16.851 3 17.78 3 18.926 3 20.07 4.165 21 5.603 21c1.437 0 2.602-.929 2.602-2.074v-6.431l4.77-.475a3 3 0 0 1-.077-.173l-.572-1.395-1.4-.57a2.7 2.7 0 0 1-1.576-1.65M14.452 13.38v2.475a3 3 0 0 0-.521-.041c-1.437 0-2.603.929-2.603 2.074 0 1.146 1.166 2.075 2.603 2.075s2.603-.929 2.603-2.075V13.36a2.86 2.86 0 0 1-2.082.02M10.96 7.56a1.02 1.02 0 0 1 .647-1.004l1.67-.68a1.04 1.04 0 0 0 .57-.567l.682-1.664c.352-.86 1.575-.86 1.927 0l.682 1.664c.106.258.311.463.57.568l1.67.68c.344.14.551.417.621.722.017.407-.199.822-.646 1.004l-1.67.68c-.26.105-.465.31-.57.568l-.682 1.663c-.353.86-1.576.86-1.928 0l-.682-1.663a1.04 1.04 0 0 0-.57-.569l-1.67-.679a1.02 1.02 0 0 1-.62-.723" />
                  </svg>
                  <span>Start Dancing</span>
                </div>
              </button>

              <p 
                className="mt-6 text-sm text-[rgb(107,114,128)]"
                style={{
                  letterSpacing: "-0.01em",
                }}
              >
                {!playerCount ? 'Select the number of players to begin' : 'Ready to dance!'}
              </p>
            </div>
          </div>

        {/* Footer */}
          <div className="absolute bottom-0 left-0 right-0 z-10 p-8 text-center">
            <p className="text-[rgb(107,114,128)] text-xs font-normal" style={{ letterSpacing: "-0.01em" }}>
            Powered by{" "}
            <a
              href="https://suno.com"
              target="_blank"
              rel="noopener noreferrer"
                className="text-[rgb(156,163,175)] hover:text-white transition-colors"
            >
              Suno
            </a>
              {" · Built with ❤️ by Krish, Eric, and Fahmi"}
            </p>
          </div>
        </div>
      </div>
    );
  }

  // STAGE 2: Loading Screen
  if (stage === 'loading') {
    return (
      <div className="h-screen w-full bg-[#101012] overflow-hidden">
        <div className="relative flex h-full w-full flex-col overflow-hidden">
          {/* Background Image with Gradient */}
          <div className="absolute inset-0 z-0 h-full w-full">
            <div
              className="absolute inset-0 h-full w-full"
              style={{
                backgroundImage: `url(https://cdn-o.suno.com/Aura-1-Hero-Web.jpg)`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                mixBlendMode: "screen",
              }}
            />
            <div
              className="absolute inset-0"
              style={{
                background: `linear-gradient(180deg, rgba(16, 16, 18, 0.00) 0%, #101012 100%)`,
              }}
            />
          </div>

          {/* Loading UI */}
          <div className="relative z-10 flex min-h-screen flex-col items-center justify-center px-4">
            <div className="w-full max-w-2xl text-center">
              {/* Loading Spinner */}
              <div className="mb-8 flex justify-center">
                <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-white"></div>
              </div>

              {/* Message Display */}
              <div className="bg-white/10 backdrop-blur-md rounded-xl p-8">
                <h2 
                  className="text-3xl font-medium text-white mb-4"
                  style={{
                    letterSpacing: "-0.02em",
                  }}
                >
                  {message}
                </h2>
                <p 
                  className="text-[rgb(156,163,175)] text-lg"
                  style={{
                    letterSpacing: "-0.01em",
                  }}
                >
                  This may take a minute...
                </p>
                
                {motionError && (
                  <div className="mt-6 p-4 bg-red-500/20 rounded-lg">
                    <p className="text-red-300">{motionError}</p>
                    <button
                      onClick={() => setStage('landing')}
                      className="mt-4 px-6 py-2 bg-white text-[#101012] rounded-full hover:bg-[rgba(255,255,255,0.9)] transition-all"
                    >
                      Go Back
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // STAGE 3: Ready Screen
  if (stage === 'ready') {
    return (
      <div className="h-screen w-full bg-[#101012] overflow-hidden">
        <div className="relative flex h-full w-full flex-col overflow-hidden">
          {/* Background Image with Gradient */}
          <div className="absolute inset-0 z-0 h-full w-full">
            <div
              className="absolute inset-0 h-full w-full"
              style={{
                backgroundImage: `url(https://cdn-o.suno.com/Aura-1-Hero-Web.jpg)`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                mixBlendMode: "screen",
              }}
            />
            <div
              className="absolute inset-0"
              style={{
                background: `linear-gradient(180deg, rgba(16, 16, 18, 0.00) 0%, #101012 100%)`,
              }}
            />
          </div>

          {/* Ready Message */}
          <div className="relative z-10 flex min-h-screen flex-col items-center justify-center px-4">
            <ReadyCountdown onComplete={() => setStage('dancing')} />
          </div>
        </div>
      </div>
    );
  }

  // STAGE 4: Dancing with background video
  return (
    <div className="fixed inset-0 w-full h-full overflow-hidden">
      {/* Audio element (hidden) */}
      <audio ref={audioRef} src={audioUrl} loop />

      {/* Just Dance background video (muted) */}
      <iframe
        src={`https://www.youtube.com/embed/${backgroundVideoId}?autoplay=1&mute=1&controls=0&showinfo=0&modestbranding=1&loop=1&playlist=${backgroundVideoId}&disablekb=1&fs=0&iv_load_policy=3&rel=0&playsinline=1&enablejsapi=0`}
        className="absolute top-1/2 left-1/2 w-[177.77vh] h-[56.25vw] min-w-full min-h-full -translate-x-1/2 -translate-y-1/2"
        allow="autoplay; encrypted-media"
        frameBorder="0"
        style={{ pointerEvents: 'none', border: 'none', zIndex: 0 }}
        title="Just Dance Background"
      />
      
      {/* Skeleton dancing in the middle */}
      <div className="absolute inset-0 z-10 flex items-center justify-center" style={{ paddingTop: '80px' }}>
        <div className="relative">
          <div style={{ filter: 'drop-shadow(0 0 20px rgba(0, 0, 0, 0.8)) drop-shadow(0 0 40px rgba(0, 0, 0, 0.5))' }}>
            <AnimatedSkeleton
              landmarks={referenceLandmarks}
              width={800}
              height={1000}
            />
          </div>
        </div>
      </div>

      {/* Feedback text above skeleton - separate fixed element */}
      {feedbackText && (
        <div
          className={`fixed top-[10%] left-1/2 -translate-x-1/2 z-[9999] transition-all duration-300 ${
            showFeedback ? 'opacity-100 scale-100' : 'opacity-0 scale-75'
          }`}
          style={{
            pointerEvents: 'none',
          }}
        >
          <div
            className="text-6xl font-bold text-white px-8 py-4 rounded-2xl whitespace-nowrap"
            style={{
              textShadow: '0 0 30px rgba(0, 0, 0, 0.8), 0 0 60px rgba(0, 0, 0, 0.6)',
              letterSpacing: '-0.02em',
              background: 'linear-gradient(135deg, rgba(139, 92, 246, 0.5), rgba(236, 72, 153, 0.5))',
              backdropFilter: 'blur(10px)',
              border: '2px solid rgba(255, 255, 255, 0.3)',
              animation: showFeedback ? 'feedbackBounce 0.5s ease-in-out' : 'none',
            }}
          >
            {feedbackText}
          </div>
        </div>
      )}

      {/* Progress Bar - Top of screen */}
      <div className="absolute top-0 left-0 right-0 z-30 h-2 bg-black/30">
        <div
          className="h-full bg-gradient-to-r from-purple-500 via-pink-500 to-orange-500 transition-all duration-100"
          style={{
            width: `${Math.min(100, (currentTime / (motionMetadata?.duration || audioDuration || 30)) * 100)}%`,
          }}
        />
      </div>

      {/* End Song Button - Top Right */}
      <div className="absolute top-6 right-6 z-30">
        <button
          onClick={handleEndSong}
          className="px-6 py-3 rounded-full bg-black/50 hover:bg-black/70 text-white font-medium transition-all border border-white/20 backdrop-blur-md"
          style={{
            letterSpacing: "-0.01em",
            textShadow: "0 0 10px rgba(0, 0, 0, 0.5)",
          }}
        >
          End Song
        </button>
      </div>

      {/* Live Pose Tracker - Bottom Left */}
      <div className="absolute bottom-8 left-8 z-20 w-80">
        <LivePoseTracker
          referenceLandmarks={referenceLandmarks}
          isActive={true}
          onScoreUpdate={(score) => {
            console.log("Score update received:", score);
            currentScoreRef.current = score; // Update ref immediately
            setCurrentScore(score); // Update state for any UI that needs it
          }}
        />
      </div>

      {/* Pose Timeline at bottom right - Just Dance style */}
      <div className="absolute bottom-8 right-8 z-20 h-72 w-[600px] overflow-hidden">
        {/* Timeline track */}
        <div className="relative h-full">
          {/* Match line indicator (underline at fixed position) */}
          <div 
            className="absolute left-[140px] bottom-0 w-[80px] h-1 bg-gray-300 z-30"
            style={{
              filter: 'drop-shadow(0 0 4px rgba(255, 255, 255, 0.8)) drop-shadow(0 0 8px rgba(0, 0, 0, 0.6))'
            }}
          />

          {/* Scrolling poses container */}
          <div className="relative h-full flex items-center">
            {downbeatTimestamps.map((timestamp) => {
              // Calculate position: move from right to left based on time difference
              // When timestamp matches currentTime, it should be at the match line (100px from left)
              const timeDiff = timestamp - (currentTime % (motionMetadata?.duration || audioDuration || 30));
              const position = 100 + (timeDiff * 160); // 160px per second (2x spacing and speed)

              const landmarks = poseSnapshots.get(timestamp);
              if (!landmarks) return null;

              // Only render if within reasonable view range (expanded for larger skeletons)
              if (position < -250 || position > 900) return null;

              // Detect if pose is hitting the match line (within 0.15s)
              const isHitting = Math.abs(timeDiff) < 0.15;
              const hasHit = timeDiff < -0.15;

              return (
                <div
                  key={timestamp}
                  className={`absolute ${
                    isHitting ? 'pose-hit-animation' : ''
                  }`}
                  style={{
                    left: `${position}px`,
                    transition: 'none',
                    opacity: hasHit ? 0 : 1,
                    display: hasHit ? 'none' : 'block',
                    filter: 'drop-shadow(0 0 10px rgba(0, 0, 0, 0.9)) drop-shadow(0 0 20px rgba(0, 0, 0, 0.6))',
                  }}
                >
                  {/* Mini skeleton - no background, just shadow */}
                  <AnimatedSkeleton
                    landmarks={landmarks}
                    width={200}
                    height={260}
                  />
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* CSS for hit animation */}
      <style jsx>{`
        @keyframes poseHit {
          0% {
            transform: translateY(0) scale(1);
          }
          50% {
            transform: translateY(-10px) scale(1.1);
          }
          100% {
            transform: translateY(-30px) scale(0.8);
            opacity: 0;
          }
        }

        .pose-hit-animation {
          animation: poseHit 0.3s ease-out forwards;
        }

        @keyframes feedbackBounce {
          0% {
            transform: translateY(0) scale(1);
          }
          50% {
            transform: translateY(-8px) scale(1.05);
          }
          100% {
            transform: translateY(0) scale(1);
          }
        }
      `}</style>

      {/* Score Modal */}
      {showScoreModal && (
        <ScoreModal
          score={finalScore}
          onClose={() => {
            setShowScoreModal(false);
            setStage('landing');
            setDownbeatScores([]);
            lastProcessedDownbeat.current = -1;
            setCurrentScore(0);
          }}
          onReplay={() => {
            setShowScoreModal(false);
            setDownbeatScores([]);
            lastProcessedDownbeat.current = -1;
            setCurrentScore(0);
            setStage('ready');
          }}
        />
      )}
    </div>
  );
}
